#ifndef __TCP_SERVER_HPP__
#define __TCP_SERVER_HPP__
#include <iostream>
#include <string>
#include <string.h>
#include <pthread.h>

#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "MyPthread/Log.hpp"
#include "MyPthread/ThreadPool.hpp"
#include "Protocol.hpp"
#include "InetAddr.hpp"

using namespace LogModule;
using namespace ThreadModule;

// 最大连接数为8
#define BACKLOG 8

const static int gsockfd = -1;
// const static std::string gdefaultip = "127.0.0.1"; // 表示本地主机

using task_t = std::function<void()>;
using handler_t = std::function<std::string(std::string &package)>;
class TcpServer;

struct ThreadData
{
    TcpServer *_this;
    int _sockfd;
    InetAddr _client;
    ThreadData(TcpServer *t, int sockfd, InetAddr client)
        : _this(t), _sockfd(sockfd), _client(client)
    {
    }
};

class TcpServer
{
private:
    void HandlerRequest(int sockfd, InetAddr client)
    {
        LOG(LogLevel::INFO) << "HandlerRequest, sockfd is : " << sockfd;

        // LOG(LogLevel::INFO) << "HandlerRequest success :" << client.Ip() << ":" << client.Port();
        char buffer[1024];
        std::string package;
        std::string response;
        while (true)
        {
            int n = ::recv(sockfd, buffer, sizeof(buffer) - 1, 0);

            if (n > 0)
            {
                buffer[n] = 0;
                package += buffer;

                response = _handler(package);
            }
            else if (n == 0)
            {
                // read 如果读取返回值是0，表示client退出
                LOG(LogLevel::INFO) << "client quit: " << sockfd;
                break;
            }
            else
            {
                // 读取失败了
                break;
            }

            ::send(sockfd, response.c_str(), response.size(), 0);
        }
        ::close(sockfd);
        LOG(LogLevel::INFO) << "close sockfd: " << sockfd;
    }

    static void *ThreadEntry(void *args)
    {
        ThreadData *threadData = (ThreadData *)args;
        threadData->_this->HandlerRequest(threadData->_sockfd, threadData->_client);

        return nullptr;
    }

public:
    TcpServer(uint16_t server_port = gserver_port)
        : _listen_sockfd(gsockfd), _server(server_port), _isrunning(false)
    {
    }
    ~TcpServer()
    {
    }
    void InitServer()
    {
        // 1. 创建监听socket
        _listen_sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sockfd < 0)
        { // socket 失败返回 -1
            LOG(LogLevel::FATAL) << "create socket failed, errno: " << errno;
            Die(SOCKET_ERR);
        }

        // 2. bind绑定地址到内核中
        int rn = ::bind(_listen_sockfd, CONV(_server.NetAddr()), _server.NetAddrLen());
        if (rn < 0)
        {
            LOG(LogLevel::FATAL) << "bind failed";
            Die(1);
        }
        LOG(LogLevel::INFO) << "bind success";

        // 3. cs,tcp是面向连接的，就要求tcp随时随地等待被连接
        // tcp 需要将socket设置成为监听状态
        rn = ::listen(_listen_sockfd, BACKLOG);
        if (rn < 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, sockfd is : " << _listen_sockfd;
    }
    void RegisterSerive(handler_t handler)
    {
        _handler = handler;
    }

    void Start()
    {
        _isrunning = false;
        // 2.2 对端地址，定义对端数据结构
        struct sockaddr_in peer;
        while (true)
        {
            socklen_t len = sizeof(peer);
            // 3.获取连接
            int sockfd = ::accept(_listen_sockfd, CONV(&peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error: " << strerror(errno);
                LOG(LogLevel::WARNING) << "_listen_sockfd: " << _listen_sockfd;

                continue;
            }
            // LOG(LogLevel::DEBUG) << "accept success sockfd: " << sockfd;

            // // // version-3: 线程池版本，适合短任务
            ThreadPoolMoudule::ThreadPool<task_t>::getInstance()
                ->Enqueue(std::bind(&TcpServer::HandlerRequest, this, sockfd, InetAddr(peer)));
            LOG(LogLevel::DEBUG) << "线程池处理一个请求...";
        }
        _isrunning = false;
    }

private:
    int _listen_sockfd;
    InetAddr _server;
    // InetAddr _client;
    bool _isrunning; // 服务器运行状态

    // 业务
    handler_t _handler;
};

#endif